<template>
<div class="app-container">
  <div style="width: 800px">
    <el-form ref="form" :rules="rules" :model="form" label-width="120px">
      <el-form-item label="试卷名称" prop="name">
        <el-input size="small" v-model="form.name" placeholder="请输入试卷名称" />
      </el-form-item>
      <el-form-item label="试卷描述" prop="des">
        <el-input size="small" v-model="form.des" placeholder="请输入试卷描述" />
      </el-form-item>
      <el-form-item label="试卷海报" required>
        <div style="color:#999">
          建议尺寸714*344px或2：1，JPG、PNG格式， 图片小于5M。
        </div>
        <el-upload
          :class="uploadUrl!=''?'hiddenUpload':''"
          action="https://service.bairicun.com/file/upload"
          list-type="picture-card"
          :on-success="handleSuccess"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove">
          <i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog :visible.sync="dialogVisible">
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-dialog>
      </el-form-item>
      <!-- <el-form-item label="试卷时间" prop="activityTime">
        <el-date-picker
          style="width:100%;"
          size="small"
          v-model="form.activityTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          align="right">
        </el-date-picker>
      </el-form-item> -->
      <!-- <el-form-item label="报名时间" prop="baoTime">
        <el-date-picker
          style="width:100%;"
          size="small"
          v-model="form.baoTime"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd HH:mm:ss"
          align="right">
        </el-date-picker>
      </el-form-item> -->
      <el-form-item label="批卷教师" prop="teacherId">
        <el-select style="width:100%;" clearable size="small" v-model="form.teacherId" placeholder="请选择主讲教师">
          <el-option
            v-for="(item,index) in teacherList"
            :key="index"
            :label="item.realName"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="答题时长" prop="answerTime">
        <el-input size="small" v-model="form.answerTime" placeholder="请输入答题时长" />
      </el-form-item>
      <!-- <el-form-item label="试卷详情" prop="detail">
        <tinymce v-model="form.detail" :height="300" placeholder="请输入试卷详情"/>
      </el-form-item> -->
      <el-form-item label="单选题目">
        <div style="display:flex;line-height:1;align-items:center; ">
          <div>
            已选择{{singleList.length}}题
          </div>
          <el-button style="margin-left:10px;" size="small" type="primary" @click="openQuestion(1)">选择题目</el-button>
          <div style="display:flex;align-items:center;margin-left:50px;">
            排序：<el-input size="small" style="width:100px;" v-model="singleSort" placeholder="请输入排序" />
          </div>
          <div style="display:flex;align-items:center;margin-left:50px;">
            分值：<el-input @input="totalScore" size="small" style="width:200px;" v-model="singleScore" placeholder="请输入分值" />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="多选题目">
        <div style="display:flex;line-height:1;align-items:center; ">
          <div>
            已选择{{doubleList.length}}题
          </div>
          <el-button style="margin-left:10px;" size="small" type="primary" @click="openQuestion(2)">多选题目</el-button>
          <div style="display:flex;align-items:center;margin-left:50px;">
            排序：<el-input size="small" style="width:100px;" v-model="doubleSort" placeholder="请输入排序" />
          </div>
          <div style="display:flex;align-items:center;margin-left:50px;">
            分值：<el-input @input="totalScore" size="small" style="width:200px;" v-model="doubleScore" placeholder="请输入分值" />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="判断题目">
        <div style="display:flex;line-height:1;align-items:center; ">
          <div>
            已选择{{judgeList.length}}题
          </div>
          <el-button style="margin-left:10px;" size="small" type="primary" @click="openQuestion(3)">判断题目</el-button>
          <div style="display:flex;align-items:center;margin-left:50px;">
            排序：<el-input size="small" style="width:100px;" v-model="judgeSort" placeholder="请输入排序" />
          </div>
          <div style="display:flex;align-items:center;margin-left:50px;">
            分值：<el-input @input="totalScore" size="small" style="width:200px;" v-model="judgeScore" placeholder="请输入分值" />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="简答题目">
        <div style="display:flex;line-height:1;align-items:center; ">
          <div>
            已选择{{shortList.length}}题
          </div>
          <el-button style="margin-left:10px;" size="small" type="primary" @click="openQuestion(4)">简答题目</el-button>
          <div style="display:flex;align-items:center;margin-left:50px;">
            排序：<el-input size="small" style="width:100px;" v-model="shortSort" placeholder="请输入排序" />
          </div>
          <div style="display:flex;align-items:center;margin-left:50px;">
            分值：<el-input @input="totalScore" size="small" style="width:200px;" v-model="shortScore" placeholder="请输入分值" />
          </div>
        </div>
      </el-form-item>
      <el-form-item label="总分">
        {{totalResult}}
      </el-form-item>

      <!-- <el-form-item label="试卷课程">
        <el-button size="small" type="primary" @click="openQuestion">选择课程</el-button>
      </el-form-item>
      <el-form-item label="试卷专栏">
        <el-button size="small" type="primary" @click="openQuestion">选择专栏</el-button>
      </el-form-item> -->
      <!-- <el-form-item label="试卷费用" prop="fee">
        <div style="color:#ff0000">
          注：如选择选择课程，按照课程费用计费
        </div>
        <el-input :disabled="Boolean(radio)" size="small" v-model="form.fee" placeholder="请输入费用" />
      </el-form-item> -->
      <!-- <el-form-item label="上限名额" prop="limitNum">
        <el-input size="small" v-model="form.limitNum" placeholder="请输入上限名额" />
      </el-form-item> -->
      <el-form-item>
        <el-button size="small" type="primary" @click="onSubmit('form')">保存</el-button>
        <el-button size="small" @click="onCancel">取消</el-button>
      </el-form-item>
    </el-form>

    <el-dialog width="1200px" top="10vh" title="选择试卷课程" :visible.sync="modalVisible">
      <div style="display:flex;align-items: center;justify-content: space-between;margin:0 0 10px;">
        <div style="display:flex;align-items: center;">
          <el-form :inline="true" class="demo-form-inline">
            <el-form-item label="课程名称">
              <el-input clearable size="small" v-model="formInline.title" placeholder="标题"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button size="small" type="primary" @click="onSubmit">搜索</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
      <el-table row-key="id" style="width: 100%" @select-all="selectAll" @select="handleSelectionChange" ref="multipleTable" v-loading="listLoading" :data="tableList" element-loading-text="Loading" border fit highlight-current-row empty-text="暂无数据">
        <el-table-column

          type="selection"
          width="80">
        </el-table-column>
        <el-table-column label="ID" width="150">
          <template slot-scope="scope">
            {{ scope.row.id }}
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" label="题目名称">
          <template slot-scope="scope">
            {{ scope.row.title }}
          </template>
        </el-table-column>
        <el-table-column v-if="questionType == 1 || questionType == 2" :show-overflow-tooltip="true" label="题目选项" width="200">
          <template slot-scope="scope">
            <div v-html="scope.row.options">

            </div>
          </template>
        </el-table-column>
        <el-table-column v-if="questionType != 4" label="题目答案" width="200">
          <template slot-scope="scope">
            {{ scope.row.answer }}
          </template>
        </el-table-column>
        <el-table-column label="题目类型" width="200">
          <template>
            <span v-if="questionType == 1">
              单选题
            </span>
            <span v-else-if="questionType == 2">
              多选题
            </span>
            <span v-else-if="questionType == 3">
              判断题
            </span>
            <span v-else>
              简答题
            </span>
          </template>
        </el-table-column>
        <el-table-column label="答案解析" width="200">
          <template slot-scope="scope">
            {{ scope.row.analysis }}
          </template>
        </el-table-column>
      </el-table>

      <div style="margin:10px 0 0 0;text-align:right;">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageObj.pageNum"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="pageObj.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageObj.total">
        </el-pagination>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align:center;">
        <el-button size="small" type="primary" @click="closeDialog">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</div>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import {
  saveApi
} from '@/api/paper'
import {
  getListApi
} from '@/api/teachers'
import {
  getListApis
} from '@/api/subject'

export default {
  components: {Tinymce},
  data() {
    return {
      radio: '',
      tableList: [],
      listLoading: false,
      formInline: {
        title: ''
      },
      form: {
        name: '',
        des: '',
        answerTime: '',
        teacherId: ''
      },
      rules: {
        name: [{
          required: true,
          message: '请输入标题',
          trigger: 'blur'
        }, ],
        des: [{
          required: true,
          message: '请输入描述',
          trigger: 'blur'
        }, ],
        teacherId: [{
          required: true,
          message: '请选择批卷教师',
          trigger: 'change'
        }, ],
      },
      dialogImageUrl: '',
      dialogVisible: false,
      uploadStatus: false,
      uploadUrl: '',
      uploadImgId: '',
      modalVisible: false,
      teacherList: [],
      questionType: 1,
      pageObj: {
        pageSize: 10,
        pageNum: 1,
        total: 0,
        name: '',
      },
      singleList: [],
      doubleList: [],
      judgeList: [],
      shortList: [],
      singleScore: '',
      singleSort: '',
      doubleScore: '',
      doubleSort: '',
      judgeScore: '',
      judgeSort: '',
      shortScore: '',
      shortSort: '',
      totalResult: 0,
    }
  },
  mounted() {
    this.getTeacherList()
  },
  methods: {
    totalScore() {
      this.totalResult = this.singleScore * this.singleList.length + this.doubleScore * this.doubleList.length + this.judgeScore * this.judgeList.length + this.shortScore * this.shortList.length
    },
    handleSelectionChange(e,row) {
      if(this.questionType == 1) {
        if(this.singleList.indexOf(String(row.id)) > -1) {
          this.singleList = this.singleList.filter((item) => {
            return item != row.id
          })
        } else {
          this.singleList.push(String(row.id))
        }
      } else if(this.questionType == 2) {
        if(this.doubleList.indexOf(String(row.id)) > -1) {
          this.doubleList = this.doubleList.filter((item) => {
            return item != row.id
          })
        } else {
          this.doubleList.push(String(row.id))
        }
      } else if(this.questionType == 3) {
        if(this.judgeList.indexOf(String(row.id)) > -1) {
          this.judgeList = this.judgeList.filter((item) => {
            return item != row.id
          })
        } else {
          this.judgeList.push(String(row.id))
        }
      } else if(this.questionType == 4) {
        if(this.shortList.indexOf(String(row.id)) > -1) {
          this.shortList = this.shortList.filter((item) => {
            return item != row.id
          })
        } else {
          this.shortList.push(String(row.id))
        }
      }
    },
    selectAll(e) {
      if(this.questionType == 1) {
        if(e.length) {
          e.forEach((item) => {
            this.singleList.push(String(item.id))
          })
          this.singleList = [...new Set(this.singleList)]
        } else {
          let tableArray = this.tableList.map(item => String(item.id))
          this.singleList = this.singleList.filter(items => {
            if (!tableArray.includes(items)) {
              return items;
            }
          })
        }
      } else if (this.questionType == 2) {
        if(e.length) {
          e.forEach((item) => {
            this.doubleList.push(String(item.id))
          })
          this.doubleList = [...new Set(this.doubleList)]
        } else {
          let tableArray = this.tableList.map(item => String(item.id))
          this.doubleList = this.doubleList.filter(items => {
            if (!tableArray.includes(items)) {
              return items;
            }
          })
        }
      } else if (this.questionType == 3) {
        if(e.length) {
          e.forEach((item) => {
            this.judgeList.push(String(item.id))
          })
          this.judgeList = [...new Set(this.judgeList)]
        } else {
          let tableArray = this.tableList.map(item => String(item.id))
          this.judgeList = this.judgeList.filter(items => {
            if (!tableArray.includes(items)) {
              return items;
            }
          })
        }
      } else if (this.questionType == 4) {
        if(e.length) {
          e.forEach((item) => {
            this.shortList.push(String(item.id))
          })
          this.shortList = [...new Set(this.shortList)]
        } else {
          let tableArray = this.tableList.map(item => String(item.id))
          this.shortList = this.shortList.filter(items => {
            if (!tableArray.includes(items)) {
              return items;
            }
          })
        }
      }
    },
    getTeacherList() {
      getListApi({
        pageNum: 1,
        pageSize: 1000
      }).then((res) => {
        this.teacherList = res.data.result
      })
    },
    handleSizeChange(val) {
      this.pageObj.pageSize = val
      this.getQuestionList()
    },
    handleCurrentChange(val) {
      this.pageObj.pageNum = val
      this.getQuestionList()
    },
    chooseone(row){
      this.radio = row.id
    },
    handleRemove(file, fileList) {
      this.uploadUrl = ''
      this.uploadImgId = ''
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess(e) {
      if(e.code == 200) {
        this.uploadStatus = true
        this.uploadUrl = e.data.url
        this.uploadImgId = e.data.id
      }
    },
    closeDialog() {
      this.modalVisible = false
      this.totalScore()
    },
    onSubmit(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if(this.uploadImgId === '') {
            this.$message.error('请上传试卷海报！');
          } else {
            saveApi({
              paperType: 1,
              paperName: this.form.name,
              description: this.form.des,
              picId: this.uploadImgId,
              answerTime: this.form.answerTime,
              markTeacher: this.form.teacherId,
              singleChoice: {
                questionSort: this.singleSort,
                questionScore: this.singleScore,
                questionIds: this.singleList.toString()
              },
              multipleChoice: {
                questionSort: this.doubleSort,
                questionScore: this.doubleScore,
                questionIds: this.doubleList.toString()
              },
              judgment: {
                questionSort: this.judgeSort,
                questionScore: this.judgeScore,
                questionIds: this.judgeList.toString()
              },
              shortAnswer: {
                questionSort: this.shortSort,
                questionScore: this.shortScore,
                questionIds: this.shortList.toString()
              },
            }).then((res) => {
              this.$message.success('操作成功！');
              setTimeout(() => {
                this.$router.back(-1)
              }, 1000);
            })
          }
        } else {
          return false;
        }
      });
    },
    onCancel() {
      this.$router.back(-1)
    },
    openQuestion(type) {
      this.pageObj.pageNum = 1
      this.pageObj.pageSize = 10
      this.pageObj.name = ''
      this.questionType = type
      this.modalVisible = true
      this.getQuestionList()
    },
    getQuestionList() {
      this.listLoading = true
      getListApis({
        pageNum: this.pageObj.pageNum,
        pageSize: this.pageObj.pageSize,
        type: this.questionType,
        name: this.pageObj.name
      }).then((res) => {
        this.listLoading = false
        this.tableList = res.data.result
        this.pageObj.total = res.data.total
        let that=this
        this.$nextTick(() => {
          // this.$refs["multipleTable"].clearSelection();
          if(this.questionType == 1) {
            for(let i=0;i<that.tableList.length;i++){
              for(let j=0;j<that.singleList.length;j++){
                if(that.tableList[i].id==that.singleList[j]){
                  that.$refs.multipleTable.toggleRowSelection(that.tableList[i],true)
                }
              }
            }
          } else if(this.questionType == 2) {
            for(let i=0;i<that.tableList.length;i++){
              for(let j=0;j<that.doubleList.length;j++){
                if(that.tableList[i].id==that.doubleList[j]){
                  that.$refs.multipleTable.toggleRowSelection(that.tableList[i],true)
                }
              }
            }
          } else if(this.questionType == 3) {
            for(let i=0;i<that.tableList.length;i++){
              for(let j=0;j<that.judgeList.length;j++){
                if(that.tableList[i].id==that.judgeList[j]){
                  that.$refs.multipleTable.toggleRowSelection(that.tableList[i],true)
                }
              }
            }
          } else if(this.questionType == 4) {
            for(let i=0;i<that.tableList.length;i++){
              for(let j=0;j<that.shortList.length;j++){
                if(that.tableList[i].id==that.shortList[j]){
                  that.$refs.multipleTable.toggleRowSelection(that.tableList[i],true)
                }
              }
            }
          }
        })
      })
    }
  }
}
</script>
<style>
  .hiddenUpload .el-upload--picture-card{
    display:none !important;
  }
</style>
<style scoped>
.line {
  text-align: center;
}
</style>
